package com.example.productmanagerspringboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.productmanagerspringboot.data.entity.Comment;
import com.example.productmanagerspringboot.data.vo.Response;
import com.example.productmanagerspringboot.data.vo.ResponseWithData;
import com.example.productmanagerspringboot.mapper.CommentMapper;
import com.example.productmanagerspringboot.utils.UserRedisUtils;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/comment")
@Slf4j
@Api(tags = "评论")
public class CommentController {
    private final CommentMapper mapper;
    private final UserRedisUtils userRedisUtils;

    public CommentController(CommentMapper mapper, UserRedisUtils userRedisUtils) {
        this.mapper = mapper;
        this.userRedisUtils = userRedisUtils;
    }

    @GetMapping("/list/{id}")
    @Operation(summary = "展示评论")
    public ResponseEntity<ResponseWithData<List<Comment>>> comment(@PathVariable("id") int id) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", id);
        List<Comment> comments = mapper.selectList(queryWrapper);
        return ResponseEntity.ok(new ResponseWithData<>("成功", 200, comments));
    }

    @PostMapping("/add")
    @Operation(summary = "添加评论")
    public ResponseEntity<Response> addComment(@RequestBody Comment comment) {
        Response response = new Response();
        if (comment.getDate() == null) comment.setDate(new Date());
        comment.setUserId(userRedisUtils.getUserId());
        if (mapper.insert(comment) <= 0) {
            response.setResultCode(500);
            response.setMessage("新增失败");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        } else {
            response.setResultCode(200);
            response.setMessage("新增成功");
            return ResponseEntity.ok().body(response);
        }
    }
}
